<template>
  <div class="shop" v-loading="exportLoading">
      <div>
        <div style="width:100%;height:32px;">
          <!-- <el-button size="mini" type="danager" @click="isCheckMemberCard = !isCheckMemberCard">可用卡号段检测</el-button> -->
          <el-button size="mini" type="primary" style="float:right;margin-left:12px;" @click="bindMemmberBtnClick">绑卡</el-button>
          <el-button size="mini" type="primary" style="float:right;margin-left:12px;" @click="isCreateXiCard = !isCheckMemberCard">创建</el-button>
          <el-button size="mini" type="primary" style="float:right;margin-left:12px;" @click="exportMemberCardData">批量导出</el-button>
        </div>
        <div style="margin-top:6px;">
          <span style="font-size:12px;">是否绑卡:</span>
          <el-select
          style="width:120px;margin-left:6px;"
          v-model="form.shop_status"
          filterable
          placeholder="全部"
          size="mini"
          @change="onChangeShopStatus"
        >
          <el-option
            v-for="item in shopstatusList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>

        <span style="font-size:12px;margin-left:12px;">是否开卡:</span>
         <el-select
          style="width:100px;margin-left:6px;"
          v-model="form.card_status"
          filterable
          size="mini"
          placeholder="全部"
          @change="onChangeCardStatus"
        >
          <el-option
            v-for="item in cardstatusList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-input size="mini" v-model="form.start_number" placeholder="起始卡号段" style="width:140px;margin-left:12px;"></el-input>---
        <el-input size="mini" v-model="form.end_number" placeholder="结束卡号段" style="width:140px;margin-left:-2px;"></el-input>
        <el-button size="mini" type="primary" @click="searchMemberCard" style="float:right;margin-left:4px">搜索</el-button>
        <el-input size="mini" v-model="form.keywords" placeholder="输入卡号或卡号ID搜索" style="width:140px;float:right;"></el-input>
        </div>
      </div>

    <el-table
      :data="tableData"
      border
      fixed
      style="margin-top:20px;"
      size="mini"
      max-height="680"
      :cell-style="tc"
      :header-cell-style="tccolor"
      ref="table"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" label="全部"></el-table-column>
      <el-table-column prop="id" label="卡号id"></el-table-column>
      <el-table-column prop="card_number" label="会员卡号" width="160"></el-table-column>
       <el-table-column  label="卡密">
         <template slot-scope="scope">
           <p v-if="scope.row.password">{{scope.row.password}}</p>
           <p v-else>---</p>
         </template>
       </el-table-column>
      <el-table-column  label="红包金额">
        <template slot-scope="scope">
          <p v-if="scope.row.price">¥ {{scope.row.price}}</p>
          <p v-else>---</p>
        </template>
      </el-table-column>
      <el-table-column label="优惠金">
        <template slot-scope="scope">
          <p v-if="scope.row.preferential_price">¥ {{scope.row.preferential_price}}</p>
          <p v-else>---</p>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" width="160" label="创建时间"></el-table-column>
      <el-table-column label="是否绑卡">
        <template slot-scope="scope">
          <p v-if="scope.row.shop_id">已绑定</p>
          <p v-else>未绑定</p>
        </template>
      </el-table-column>
      <el-table-column label="是否开卡">
        <template slot-scope="scope">
          <p v-if="scope.row.uid >0">已开卡</p>
          <p v-else>未开卡</p>
        </template>
      </el-table-column>
      <el-table-column label="开卡用户" prop="uid"></el-table-column>
      <el-table-column label="开卡时间" prop="bind_user_time" width="160"></el-table-column>
      <el-table-column label="操作" fixed="right" width="280">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="danager" @click="openMemberCardDetail(scope.row.id)">详情</el-button> -->
          <el-popover placement="bottom-end" width="300" trigger="click">
            <img style="height:300px;width:300px;" :src="qrCodeUrl" alt />
            <el-button
              slot="reference"
              size="mini"
              class="qrBtn"
              type="danager"
              @click="openMemberQRcode(scope.row.id)"
            >物料二维码</el-button>
          </el-popover>
          <!-- <el-button
              slot="reference"
              size="mini"
              type="danager"
              @click="openMemberQRcode(scope.row.card_number)"
          >物料二维码</el-button>-->
          <el-button size="mini" type="primary" @click="deleteMemberCard(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-col :span="24">
      <div class="pagination">
        <el-pagination
          background
          @current-change="pageChange"
          :current-page="form.page"
          :page-size="form.size"
          layout="total, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-col>

    <jdialog title="会员卡详情" :visible.sync="isShowMemberDetail" width="800px">
      <member-detail
        :visible="isShowMemberDetail"
        :currentId="currentId"
        @close="isShowMemberDetail = false"
        @showMemberDetail="cancelShowMemberDetail"
      ></member-detail>
    </jdialog>

    <!--卡号段检测-->
    <jdialog title="卡号段检测" :visible.sync="isCheckMemberCard" width="600px">
      <el-row class="check_select_member">
        <el-col :span="24" class="add_member_num">
          输入需要检测的卡号段范围，系统会给出卡号段结果
        </el-col>
        <el-col :span="20" class="add_member_num">
          <el-input style="width:40%;" v-model="start" placeholder="起始卡号段" clearable></el-input>-------<el-input
            style="width:40%;"
            v-model="end"
            placeholder="末尾卡号段"
            clearable
          ></el-input>
        </el-col>
        <el-col :span="4" class="card_number">卡数量: {{number}}</el-col>
      </el-row>
      <el-row>
        <el-col :span='24' >
          <el-button class="check_member_num" size="mini" type="primary" @click="CheckCardNumber">检测</el-button>
          </el-col>
      </el-row>
    </jdialog>
    <!--添加卡号段-->
    <jdialog title="创建会员卡" :visible.sync="isShowADDMember" width="600px">
      <el-form class="add_membercard">
        <div class="tip_note">提示：请确保创建的卡号段是没有使用的空号段;</div>
        <el-form-item v-for="(item,index) of AddCardList" :key="index" class="select_member">
          <el-col :span="24">
            <div class="member_order">{{item.num}}</div>输入需要创建的卡号，会员卡号由系统根据规则生成
            <i
              v-if="index > 0"
              class="el-icon-close delete_shoplist"
              @click="deleteMemberlistdata(index)"
            ></i>
          </el-col>
          <el-col :span="20" class="add_member_num">
            <el-input style="width:40%;" v-model="item.start" placeholder="起始卡号段" clearable></el-input>-------
            <el-input
              style="width:40%;"
              v-model="item.end"
              placeholder="末尾卡号段"
              clearable
              @blur="getCardNumber(index)"
            ></el-input>
          </el-col>
          <el-col :span="4" class="card_number">卡数量: {{item.cardNumber}}</el-col>
        </el-form-item>

        <el-form-item>
          <div class="add_shop" @click="addShopGroupFormlist">+ 添加分号段</div>
        </el-form-item>
      </el-form>

      <div class="class_btn">
        <el-button size="mini" @click="isShowADDMember = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="certainAddmemberCard">创建</el-button>
      </div>
    </jdialog>

    <jdialog title="创建喜卡" :visible.sync='isCreateXiCard' width='540px'>
      <el-form style="padding:20px;" v-loading='loading'>
        <el-form-item label="起始卡号:">
          <el-input disabled type="text" style="width:360px;" v-model="last_id">
            <el-button slot="append" type="primary"
      v-clipboard:copy="last_id"
      v-clipboard:success="onCopy"
      v-clipboard:error="onError">复制</el-button>
          </el-input>
          <p style="color:#999999; font-size:12px;margin-left:72px;">起始卡号系统自动分配，不允许修改；</p>
        </el-form-item>

        <el-form-item label="创卡数量:">
          <el-input type="number" min="0" style='width:360px;' v-model='XiCardNumber'>
            <p
            slot="suffix">张</p>
          </el-input>
        </el-form-item>
      </el-form>

    <div style="text-align:center;margin-bottom:20px;">
      <el-button size="mini" @click="cancelCreateXicard">取消</el-button>
      <el-button size="mini" type="primary" @click="certainCreateXicard">确定</el-button>
    </div>
    </jdialog>


     <!--绑定卡号段-->
    <el-dialog title="绑定商户卡号段" :visible.sync="isAddMemberCard" center width="840px">
      <el-row>
        <el-col :span="4">
          <el-button size="mini" type="primary" @click="selectShopSeller">选择绑定商家</el-button>
        </el-col>
        <el-col :span="20">
          <div v-if="selectShopDetail.name" class="bind_shop">已绑定：{{selectShopDetail.name}}</div>
        </el-col>
      </el-row>
      <el-row class="bind_card_row">
        <el-col :span="8">
          <div v-if="redpacketAmount > 0" class="bind_shop">{{redpacketAmount}}</div>
          <div v-else class="bind_shop">返显红包总额</div>
        </el-col>
        <el-col :span="8">
          <div v-if="cardNumberAmount > 0" class="bind_shop">{{cardNumberAmount}}</div>
          <div v-else class="bind_shop">返显分号段总数</div>
        </el-col>
        <el-col :span="8">
          <div v-if="bindCardAmount > 0" class="bind_shop">{{bindCardAmount}}</div>
          <div v-else class="bind_shop">返显绑卡总数总额</div>
        </el-col>
      </el-row>
      <el-row class="bind_card_row" v-for="(item,index) of AddCardList" :key="index">
        <el-col :span="24">
          <div class="member_order">{{item.num}}</div>
          <i
            v-if="index > 0"
            class="el-icon-close delete_shoplist"
            @click="deleteMemberlistdata(index)"
          ></i>
        </el-col>
        <el-col :span="12">
          <el-input style="width:42%;" v-model="item.start" placeholder="起始卡号段" clearable></el-input>------
          <el-input style="width:42%;" v-model="item.end" placeholder="末尾卡号段" clearable></el-input>
        </el-col>
        <el-col :span="6">
          <el-input v-model="item.price" placeholder="输入红包配额" clearable @blur="getCardNumber" style="margin-left:12px;"></el-input>
        </el-col>
         <el-col :span="6">
          <el-input v-model="item.preferential_price" placeholder="输入优惠金配额" clearable style="margin-left:12px;"></el-input>
        </el-col>
      </el-row>
      <el-row>
        <div class="add_shop" @click="addShopGroupFormlist">+ 添加分号段</div>
      </el-row>

      <el-dialog title="选择绑定商家" :visible.sync="isShowSelectShop" center append-to-body>
        <el-form>
          <p>提示：选择商家时系统将为您过滤已参与其他联盟且仍在有效期中的商户</p>
          <el-row>
            <el-col :span="12">
              <el-input v-model="keywords" placeholder="输入商家名称搜索" clearable></el-input>
            </el-col>
            <el-button class="select_btn_shop" type="primary" @click="searchvouchlist">搜索</el-button>
          </el-row>
          <el-table
            :data="selectShopdata"
            border
            highlight-current-row
            @current-change="handleCurrentChange"
            :cell-style="tc"
            :header-cell-style="tccolor"
          >
            <el-table-column prop="name" label="商户名称"></el-table-column>
            <el-table-column prop="address" label="地址信息"></el-table-column>
            <el-table-column prop="username" label="联系人"></el-table-column>
            <el-table-column prop="tel" label="联系方式"></el-table-column>
          </el-table>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="isShowSelectShop = false">取 消</el-button>
          <el-button type="primary" @click="selectShopInfo">保存</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelMemberCard">取 消</el-button>
        <el-button type="primary" @click="submitMemberCardInfo">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// import {
//   cardXiList,
//   cardXiDelete,
//   cardXiQRcode,
//   cardXiCheck,
//   cardXiAdd,
//   cardXiBind
// } from "@/api/member";

// import  {shopSellerSelect} from "@/api/goods"
import memberDetail from "./member_detail";
import { API_BASE_URL } from "@/config";
export default {
  components: {
    memberDetail
  },
  name: "member",
  data() {
    return {
      isShowMemberDetail: false,
      isShowQrCode: false,
      isShowADDMember: false,
      isCheckMemberCard: false,
      start: "",
      end: "",
      number: 0,
      form: {
        card_status: "",
        shop_status: "",
        export: "",
        keywords: "",
        start_number:'',
        end_number:'',
        page: 1,
        size: 10
      },
      shopstatusList: [
        { id: 1, name: "已绑卡" },
        { id: 0, name: "未绑卡" }
      ],
      cardstatusList: [
        { id: 1, name: "已开卡" },
        { id: 0, name: "未开卡" }
      ],
      currentId: "",
      tableData: [],
      total: 0,
      selectedList: [],
      qrCodeUrl: "",



      //创建喜卡相关
      loading:false,
      isCreateXiCard:false,
      XiCardNumber:'',
      last_id:'',



      //绑定卡号段
      isAddMemberCard:false,
      isShowSelectShop:false,
      selectShopdata:[],
      selectShopDetail : {},
      //红包总额
      redpacketAmount: 0,
      //分号段总数
      cardNumberAmount: 0,
      //返显绑卡数总额
      bindCardAmount: 0,
      keywords: "",
      AddCardList: [],

      exportLoading:false

    };
  },
  mounted() {
    this.getXiMemberListData();
  },

  methods: {
    tc() {
      return "text-align:center; color:#333333; font-size:12px;";
    },
    tccolor() {
      return "text-align:center;background-color:#f5f5f5; font-size:14px;";
    },
    //更改绑定状态
    onChangeShopStatus(value) {
      if (value == 2) {
        this.form.shop_status = "";
      } else {
        this.form.shop_status = value;
      }
    },
    //选择卡片
    handleSelectionChange(arr) {
      this.selectedList = arr;
    },
    //更改开卡状态
    onChangeCardStatus(value) {
      if (value == 2) {
        this.form.card_status = "";
      } else {
        this.form.card_status = value;
      }
    },
    //搜索会员卡片
    searchMemberCard() {
      this.form.page  = 1;
      this.getXiMemberListData();
    },
    pageChange(page) {
      this.form.page = page;
      this.getXiMemberListData();
    },

    //删除会员卡
    deleteMemberCard(id) {
      this.$confirm("确定删除该会员卡?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        //删除会员卡
        this.getcardXiDeleteData(id);
      });
    },
    //导出
    exportMemberCardData() {
      this.exportLoading  = true;
      this.form.export = 1;
      this.getXiMemberListData();
    },
    //删除会员卡
    async getcardXiDeleteData(id) {
      let res = await cardXiDelete({ id: id });
      if (res.code === 10000) {
        this.$message.success("删除成功");
        this.getXiMemberListData();
      } else {
        this.$message.error(res.message);
      }
    },
    //检测卡号段
    CheckCardNumber() {
      console.log(1)
      this.CheckCardAmoutNumber();
    },
    async CheckCardAmoutNumber() {

      console.log({ start: this.start, end: this.end })
      let res = await cardXiCheck({ start: this.start, end: this.end });
      if (res.code === 10000) {
        this.number = res.data.amount_able;
      } else {
        this.$message.error(res.message);
      }
    },

    //查看详情
    openMemberCardDetail(id) {
      this.isShowMemberDetail = true;
      this.currentId = id;
    },
    cancelShowMemberDetail() {
      this.isShowMemberDetail = false;
    },

    //查看物料二维码
    openMemberQRcode(number) {
      this.getwechatMiniCodeUrl(number);
    },

    //取消创建喜卡
    cancelCreateXicard(){
      this.isCreateXiCard = false
      this.XiCardNumber = ''
    },

   //确定创建喜卡
   certainCreateXicard(){
     this.loading = true
     this.getcardXiAddData()

   },
    //删除商户
    deleteMemberlistdata(index) {
      if (this.AddCardList.length === 1) {
        this.$message.error("最少一个");
      } else {
        this.AddCardList.splice(index, 1);
        this.getCardNumber();
      }
    },
      //选择商户
    selectShopInfo() {
      if (this.selectShopDetail) {
        this.isShowSelectShop = false;
      } else {
        this.$message.error("请选择一个商家");
      }
    },
     searchvouchlist() {
      this.getshopSellerSelectList();
    },
    //绑定卡号段
    bindMemmberBtnClick() {
      (this.selectShopDetail = {}),
        (this.AddCardList = [{ num: 1, start: "", end: "", price: "" ,preferential_price:""}]);
      this.redpacketAmount = this.bindCardAmount = this.cardNumberAmount = 0;
      this.isAddMemberCard = true;
    },
    //选择绑定商家
      selectShopSeller() {
      this.isShowSelectShop = true;
      this.getshopSellerSelectList();
    },
     //添加商户
    addShopGroupFormlist() {
      if (this.AddCardList.length === 2) {
        this.$message.error("最多添加2个");
        return;
      } else {
        this.AddCardList.push({ num: 2, start: "", end: "", price: "" });
      }
    },
    cancelMemberCard() {
      this.isAddMemberCard = false;
      this.selectShopDetail = {};
    },
    //获取商户列表
    async getshopSellerSelectList() {
      let res = await shopSellerSelect({ keywords: this.keywords });
      this.selectShopdata = res.data.data;
    },
      handleCurrentChange(val) {
      this.selectShopDetail = val;
    },
     //计算红包总额、号码段总数等、
    getCardNumber() {
      this.redpacketAmount = this.cardNumberAmount = this.bindCardAmount = 0;
      for (var i = 0; i < this.AddCardList.length; i++) {
        var form = this.AddCardList[i];
        if (form.start > 0 && form.end > 0 && form.price > 0) {
          this.redpacketAmount =
            this.redpacketAmount + (form.end - form.start+1) * form.price;
          this.cardNumberAmount = i + 1;
          this.bindCardAmount = this.bindCardAmount + form.end - form.start +1;
        }
      }
    },
    async getwechatMiniCodeUrl(number) {
      let res = await cardXiQRcode({ card_number: number });
      if (res.code === 10000) {
        this.qrCodeUrl = res.data.url;
        console.log(this.qrCodeUrl);
        this.isShowQrCode = true;
      } else {
        this.$message.error(res.message);
      }
    },
    //获取喜卡列表
    async getXiMemberListData() {
      if(this.form.start_number == null){
        this.form.start_number = ''
      }
      if(this.form.end_number == null){
        this.form.end_number = ''
      }
      if (this.form.export == 1) {
        let res = await cardXiList(this.form);
        this.form.export = "";
        this.exportLoading = false
        if (res.code !== 10000) return;
        console.log(res);
        window.open(
          `${API_BASE_URL}/admin/download/zip/${res.data.download_token}`
        );
        return;
      }
      let res = await cardXiList(this.form);
      if (res.code === 10000) {
        this.tableData = res.data.data;
        this.total = res.data.total;
        this.last_id = res.data.last_id
      } else {
        this.$message.error(res.message);
      }
    },

    certainAddmemberCard() {
      //创建卡段
      for (var i = 0; i < this.AddCardList.length; i++) {
        var form = {
          start: this.AddCardList[i].start,
          end: this.AddCardList[i].end
        };
        this.getcardXiAddData(form, i);
      }
    },
            onCopy: function (e) {
              this.$message.success("已复制到剪贴板");
            },
            onError: function (e) {
            },

    //添加卡
    async getcardXiAddData() {
      let res = await cardXiAdd({number:this.XiCardNumber});
      if (res.code === 10000 ) {
        this.$message.success("添加卡成功");
              this.isCreateXiCard = false
              this.loading = false
              this.XiCardNumber = ''
              this.getXiMemberListData()
      } else {
        this.loading = false
        this.$message.error(res.message);
      }
    },

     //绑定商户卡号段
    submitMemberCardInfo() {
      if (this.selectShopDetail) {
        for (var i = 0; i < this.AddCardList.length; i++) {
          var form = {
            shop_id: this.selectShopDetail.id,
            price: this.AddCardList[i].price,
            start: this.AddCardList[i].start,
            end: this.AddCardList[i].end,
            preferential_price:this.AddCardList[i].preferential_price
          };
          this.getCardXiBindData(form, i);
        }
      } else {
        this.$message.error("必须选择一个商家绑定");
      }
    },

 //添加卡号段
    async getCardXiBindData(form, index) {
      let res = await cardXiBind(form);
      if (index === this.AddCardList.length - 1 && res.code === 10000) {
        this.$message.success("绑定卡号段成功");
        this.isAddMemberCard = false;
      } else if (index === this.AddCardList.length - 1 && res.code !== 10000) {
        this.$message.error(res.message);
      }
    },
    async getCardAmoutNumber(index) {
      var form = this.AddCardList[index];
      let res = await cardXiCheck({ start: form.start, end: form.end });
      console.log(res);
      if (res.code === 10000) {
        form.cardNumber = res.data.amount_able;
      } else {
        this.$message.error(res.message);
      }
    }
  }
};
</script>


<style lang="scss" scoped>
.shop {
  padding: 20px;


  .add_member_num {
    padding: 10px 30px;
  }
  .check_member_num{
    float: right;
    margin: 0 20px 20px 10px;
  }
  .search_row {
    margin: 12px 14px 20px 0;
  }
  .pagination {
    float: right;
  }
  .select_member {
    border: 1px dashed #a8a8a8;
  }
  .check_select_member{
    border: 1px dashed #a8a8a8;
    margin:20px;
  }
  .card_number {
    line-height: 60px;
  }
   .delete_shoplist {
    float: right;
    background-color: #f4222d;
    color: white;
    position: absolute;
    right: 0;
    top: 0;
  }
  .member_order {
    float: left;
    color: #ffffff;
    background-color: #f4222d;
    font-size: 14px;
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    margin-right: 10px;
    position: absolute;
    left: 0;
    top: 0;
  }
  .qrBtn {
    margin: 0px 10px;
  }
  .tip_note {
    margin-bottom: 10px;
    font-size: 14px;
    color: #a8a8a8;
  }
  .add_shop {
    text-align: center;
    border: 1px solid #a8a8a8;
  }
  .add_membercard {
    padding: 10px 20px;
  }
  .class_btn {
    margin-bottom: 20px;
    text-align: center;
  }
  //绑定卡号段相关
  .bind_shop {
    color: #a8a8a8;
    border: 1px solid #e5e5e5;
    // padding: 10px;
    height: 27px;
    line-height: 27px;
    text-align: center;
    margin-left: 10px;
  }
  .bind_card_row {
    border: 1px dashed #a8a8a8;
    margin: 20px 0;
    padding: 24px 20px;
    position: relative;
  }
}
</style>
